import 'dart:async';
import 'dart:io';

import 'package:flutter_sound/flutter_sound.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as pathD;
import 'package:friends_flutter/config/service/upload_service.dart';

import '../../utils/common_utils.dart';
import '../../utils/sound_call_utils.dart';
import '../app_config.dart';

class RecordService extends GetxService {
  static RecordService get to => Get.find<RecordService>();

  FlutterSoundRecorder recorderModule = FlutterSoundRecorder();
  String path = '';
  // 录音计时器。
  Timer? _timer;
  //录音时长
  int seconds = 0;

  RxString secondsLength = '00:00:00'.obs;
  RxBool isStartRecording = false.obs;
  final Codec _codec = Codec.aacMP4;

  Future<void> init() async {
      // soundCallUtils.soundInit(isLimitTime: false, (value) {
      //   switch (value) {
      //     case SoundCall.recordEnd: {
      //       //录音到了最大时间,自己结束
      //       isStartRecording.value = false;
      //       secondsLength.value = '00:00:00';
      //       File file = File(soundCallUtils.filePath);
      //       logger?.i('录音上传');
      //       logger?.i('文件名称: ${path.basename(file.path)} 录音时长: ${formatDuration(soundCallUtils.seconds)}');
      //       print('到我了11111111');
      //       UploadService.to.addUploadTask(file);
      //       break ;
      //     }
      //   }
      // }, volumeAction: (volume) {
      //   ///声音大小(分大五个等级: 从小到大1, 2, 3, 4, 5)
      // }, secondsAction: (int time) {
      //   secondsLength.value = formatDuration(time);
      // });
    // }

  }

  String formatDuration(int seconds) {
    int hours = seconds ~/ 3600;
    int minutes = (seconds % 3600) ~/ 60;
    int secs = seconds % 60;

    String hoursStr = hours.toString().padLeft(2, '0');
    String minsStr = minutes.toString().padLeft(2, '0');
    String secsStr = secs.toString().padLeft(2, '0');

    return "$hoursStr:$minsStr:$secsStr";
  }

  //开始录音
  Future<void> startRecording() async {
    if (await CommonUtil.isOpenmicrophonePermissions()) {
      logger?.i('开始录音');
      try {
        isStartRecording.value = true;
        path = await getSoundPath();
        print('录音路径: ${path}');
        await recorderModule.openRecorder().then((value) {
          print('recorderModule.openRecorder: ${value}');
        });
        recorderModule.startRecorder(
          toFile: path,
          codec: _codec,
        );
        //开启定时器
        startTimer();

        recorderModule.onProgress?.listen((event) {
          secondsLength.value = formatDuration(event.duration.inSeconds);
          print('录音时长: ${secondsLength.value}');
        });

        print('===>  开始录音');
      } catch (err) {
        print('RecordService e = $err');
      }
    }
  }

  //录音路径
  Future<String> getSoundPath() async {
    Directory? data;
    if (Platform.isIOS) {
      data = await getApplicationDocumentsDirectory();
    } else {
      data = await getExternalStorageDirectory();
    }
    String tempPath = '${data?.path ?? ''}/xdan${DateTime.now().microsecondsSinceEpoch}${ext[_codec.index]}';
    return tempPath;
  }

  //结束录音
  Future<void> endRecord() async {
    if (!isStartRecording.value) {
      return ;
    }
    try {
      _timer?.cancel();
      await recorderModule.closeRecorder();
      await recorderModule.stopRecorder();
      print('stopRecorder');
      logger?.i('录音结束');
      // soundCallUtils.stop();
      isStartRecording.value = false;
      secondsLength.value = '00:00:00';
      File file = File(path);
      logger?.i('录音上传');
      logger?.i('文件名称: ${pathD.basename(file.path)} 录音时长: ${formatDuration(seconds)}');
      print('到我了11111111');
      UploadService.to.addUploadTask(file);
      seconds = 0;
    } catch (err) {
      print('stopRecorder error: $err');
    }
  }

  /// 启动录音计时器。
  void startTimer() {
    // 计时器（`Timer`）组件的定期（`periodic`）构造函数，创建一个新的重复计时器。
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      seconds++;
      secondsLength.value = formatDuration(seconds);
    });
  }


}